<template>
  <el-card>
    <!-- 数据表格 -->
    <div class="table-container">
      <div class="mb-2.5">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-button type="primary" :icon="CirclePlus" @click="openDialogForm(true)">新增省份</el-button>
          </el-col>
          <el-col :span="12">
            <div class="flex justify-end">
              <el-button :icon="RefreshRight" circle @click="handleSearchFormReset"></el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="table-wrapper">
        <el-table
            :data="tableData"
            row-key="area_code"
            lazy
            @expand-change="handleExpandChange"
            :load="loadNode"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            style="width: 100%;">
          <el-table-column align="left" prop="id" label="ID"></el-table-column>
          <el-table-column align="left" prop="area_code" label="行政代码"></el-table-column>
          <el-table-column align="center" prop="name" label="地区名称"></el-table-column>
          <el-table-column align="center" prop="parent_name" label="上级名称"></el-table-column>
          <el-table-column align="left" label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="addSubRegion(scope.row)">添加</el-button>
              <el-button type="primary" link @click="openDialogForm(false, scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog v-model="formShow" :title="dialogTitle" width="700">
      <el-form ref="formDataRef" class="pa-5" :rules="rules" :model="formData" label-position="right"
               label-width="auto">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上级名称" prop="parent_name">
              <el-input v-model="formData.parent_name" placeholder="上级名称" disabled autocomplete="off"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地区名称" prop="name">
              <el-input v-model="formData.name" placeholder="地区名称" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, computed, nextTick} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, type FormRules} from 'element-plus'
import {RefreshRight, CirclePlus} from '@element-plus/icons-vue'
import {getRegionListApi, getRegionInfoApi, saveRegionInfoApi, updateRegionInfoApi, deleteRegionApi} from '@/api/region'

interface RegionNode {
  id: number
  code: string
  name: string
  parent_code: number
  status: number
  hasChildren: boolean
  children?: RegionNode[]
}

// 表格数据
const tableData = ref([]);
// 表单对话框
const formShow = ref(false);
// 对话框标题
const dialogTitle = computed(() => (isAdd.value ? '新增城市地区' : '编辑城市地区'));
// 提交表单ref
const formDataRef = ref<FormInstance>();
// 是否新增
const isAdd = ref(false);
// 记录已展开的节点ID
const expandedNodes = ref<Set<number>>(new Set());

// 接口类型
interface FormDataTypes {
  id?: number
  name: string
  parent_code: number
  status: number
  parent_name: string
}

// 表单数据字段
const initForm = reactive<FormDataTypes>({
  name: '',
  status: 1,
  parent_code: 0,
  parent_name: '中国',
})

// 表单数据字段
const formData = reactive<FormDataTypes>({...initForm})

const rules = ref<FormRules<FormDataTypes>>({
  name: [
    {required: true, message: '城市地区名称必填', trigger: 'change'},
  ]
});

// 处理节点展开事件
const handleExpandChange = (row: RegionNode, expanded: boolean) => {
  if (expanded) {
    expandedNodes.value.add(row.id);
  } else {
    expandedNodes.value.delete(row.id);
  }
};

// 加载根节点数据
const loadTableData = async () => {
  const response = await getRegionListApi({});
  tableData.value = response.data;
};

// 加载子节点数据
const loadNode = async (row: RegionNode,  treeNode: unknown, resolve: (data: RegionNode[]) => void) => {
  const response = await getRegionListApi({ parent_code: row.area_code });
  resolve(response.data.map(item => ({
    ...item,
    hasChildren: item.hasChildren
  })));
};

// 重置搜索表单
const handleSearchFormReset = () => {
  loadTableData(); // 重新加载初始数据
};

// 删除行数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确定删除此数据吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then( async () => {
    // 执行删除操作
    await deleteRegionApi(row.id);
    // 刷新表格数据
    await loadTableData();
    // 提示删除成功
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  })
};

// 打开对话表单
const openDialogForm = async (isNew: boolean, row?: {id: number}) => {
  formShow.value = true; // 显示对话框
  isAdd.value = isNew;

  Object.assign(formData, initForm);
  delete formData.id;
  await nextTick(() => {
    formDataRef.value.clearValidate();
    formDataRef.value.resetFields();
  });

  if (!isAdd.value) {
    // 编辑时获取城市地区信息
    const response = await getRegionInfoApi(row.id);
    Object.assign(formData, response.data); // 将接口数据合并到 formData 中
  }
};

// 添加子级地区
const addSubRegion = async (row: any) => {
  formShow.value = true; // 显示对话框
  isAdd.value = true;
  Object.assign(formData, initForm);
  formData.parent_code = row.id
  formData.parent_name = row.name
  delete formData.id;
  await nextTick(() => {
    formDataRef.value.clearValidate();
    formDataRef.value.resetFields();
  });
}

// 关闭对话表单
const handleClose = () => {
  formShow.value = false;
}

// 提交城市地区表单
// 修改后的提交处理函数
const handleSubmit = async () => {
  if (!formDataRef.value) return;
  await formDataRef.value.validate();

  const isUpdate = !!formData.id;

  try {
    if (isUpdate) {
      await updateRegionInfoApi(formData.id, formData);
      ElMessage.success('更新成功');
    } else {
      await saveRegionInfoApi(formData);
      ElMessage.success('新增成功');
    }

    handleClose();

    const parentId = formData.parent_code;

    // 递归查找父节点函数
    const findParent = (nodes: RegionNode[]): RegionNode | null => {
      for (const node of nodes) {
        if (node.id === parentId) return node;
        if (node.children) {
          const found = findParent(node.children);
          if (found) return found;
        }
      }
      return null;
    };

    if (parentId === 0) {
      // 根节点直接刷新整个表格
      await loadTableData();
    } else {
      // 1. 刷新当前层级数据
      const parentNode = findParent(tableData.value);
      if (parentNode) {
        const response = await getRegionListApi({ parent_code: parentId });
        parentNode.children = response.data.map(item => ({
          ...item,
          hasChildren: item.hasChildren
        }));

        // 强制表格更新
        tableData.value = [...tableData.value];

        // 2. 刷新下一级已展开的节点数据
        for (const child of parentNode.children) {
          if (expandedNodes.value.has(child.id)) {
            // 重新加载子节点数据
            const childResponse = await getRegionListApi({ parent_code: child.id });
            child.children = childResponse.data.map(item => ({
              ...item,
              hasChildren: item.hasChildren
            }));
            // 再次触发表格更新
            tableData.value = [...tableData.value];
          }
        }
      }
    }
  } catch (error) {
    console.error('操作失败:', error);
  }
};

onMounted(() => {
  loadTableData(); // 在组件挂载后加载数据
});
</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-wrapper {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}
</style>